import 'reflect-metadata';
import { createConnection } from 'typeorm';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import { Request, Response } from 'express';
import { Routes } from './routes';
import { webSiteRoutes } from './webSiteRoutes';
var cors = require('cors');
var path = require('path');
const { auth } = require('./middleware/auth');
const { role } = require('./middleware/role');
createConnection()
  .then(async (connection) => {
    // create express app
    const app = express();
    app.use(bodyParser.json());

    // app.use(express.static(path.join(__dirname, 'public')));
    app.use('/static', express.static(path.join(__dirname, '../../upload-location')));
    app.use(express.static(path.join(__dirname, '../../upload-location')));
    app.use(cors());
    app.use(auth);
    app.use(role);
    // register express routes from defined application routes
    Routes.forEach((route) => {
      (app as any)[route.method]('/api' + route.route, (req: Request, res: Response, next: Function) => {
        const result = new (route.controller as any)()[route.action](req, res, next);
        if (result instanceof Promise) {
          result.then((result) => (result !== null && result !== undefined ? res.send(result) : undefined));
        } else if (result !== null && result !== undefined) {
          res.json(result);
        }
      });
    });
    webSiteRoutes.forEach((route) => {
      (app as any)[route.method]('/web' + route.route, (req: Request, res: Response, next: Function) => {
        const result = new (route.controller as any)()[route.action](req, res, next);
        if (result instanceof Promise) {
          result.then((result) => (result !== null && result !== undefined ? res.send(result) : undefined));
        } else if (result !== null && result !== undefined) {
          res.json(result);
        }
      });
    });

    // setup express app here
    // ...

    // start express server
    app.listen(4000);

    console.log('程序已运行在 4000 端口. Open http://localhost:4000 to see results');
  })
  .catch((error) => console.log(error));
